package com.xlf.service.system.controller.system;

import com.xlf.common.auth.dao.UserDetailsImpl;
import com.xlf.common.auth.util.SecurityUtils;
import com.xlf.common.core.annotation.Anonymous;
import com.xlf.common.core.constant.UserConstants;
import com.xlf.common.core.pojo.mode.AjaxResult;
import com.xlf.common.core.util.StringUtils;
import com.xlf.common.redis.service.RedisCache;
import com.xlf.pojo.system.SysMenu;
import com.xlf.pojo.system.SysUser;
import com.xlf.service.system.service.SysMenuService;
import com.xlf.service.system.service.SysUserService;
import com.xlf.service.system.service.impl.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 用户消息获取
 */
@RestController
@RequestMapping("/system")
public class SysLoginController
{

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    SysMenuService menuService;

    @Autowired
    SysUserService userService;


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = ((UserDetailsImpl)SecurityUtils.getLoginUser()).getSysUser();

        if(user != null){
            user.setPassword(null);
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters()
    {
        Long userId = (Long) SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 注册用户
     */
    @Anonymous
    @PostMapping("/register")
    public AjaxResult register(@Validated @RequestBody SysUser user)
    {
        userService.register(user);
        return AjaxResult.success();
    }

}
